// 商品列表
import React, { useState, useEffect } from 'react';
import { Table, Image, Space, Button, Form, Input, Select, Modal, message, Switch, Typography, Collapse, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import zh_CN from 'antd/es/locale/zh_CN';
const { Text } = Typography;
import Add from './GoodListChild/Add';
import Check from './GoodListChild/check';
import { getListFind, sortList, researchData } from "@/api/GoodList";
import { deleteById } from "@/api/GoodList";



// 表格
interface DataType {
  goodsId: number;
  goodsImg: string;
  goodsName: string;
  goodsBrandId: number;
  goodsSell: string;
  brandName: string;
  goodsStatus: string;
  goodsPriceRange: string;
  goodsSernum: string;
  goodsSer: string;
  categoryName: string;

}

export default function GoodList() {

  const [dataSource, setDataSource] = useState<DataType[]>([])  //表格总数据




  useEffect(() => {

    getList()
    // deleteId()
    // updateGood()

  }, [])



  function getList() {
    getListFind({
      limit: 7,
      page: 1
    }).then(res => {
      console.log('获取列表', res);
      setDataSource(res.data.data)
    }).catch(err => {
      console.log('获取列表', err);
    })
  }




  const { Panel } = Collapse;//折叠面板

  const [isModalOpen3, setIsModalOpen3] = useState(false);


  const [stateDefaultValue, setStateDefaultValue] = useState('请选择')


  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsSernum',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      render: (_, record) => (
        <Image
          width={70}
          height={50}
          src="https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AAOEab5.img"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '货号',
      dataIndex: 'goodsId',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
    },
    {
      title: '是否上架',
      dataIndex: 'goodsStatus',
      render: (_, record) => (
        <Switch
          checked={record.goodsStatus == "4" ? true : false}
          onChange={onChange1} />
      ),
    },
    {
      title: '销量',
      dataIndex: 'goodsSer',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button className='edmit' onClick={() => rev(record)}>编辑</Button>

          <Button className='add' onClick={() => check(record)}>查看</Button>
          <Button className='add' onClick={() => showModal3(record)}>生成链接</Button>
          <Button id='del' onClick={() => showConfirm(record)}>删除</Button>
        </Space >
      ),
    },
  ];



  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  //弹框打开
  const showModal3 = (record: any) => {
    setIsModalOpen3(true);
    console.log('(record)----', record);

  };


  // 修改弹框确定
  const handleOk = () => {

    setIsModalOpen3(false);

  };

  //修改弹框取消
  const handleCancel = () => {
    setIsModalOpen3(false);

  };

  // 开关
  const onChange1 = (checked: boolean) => {
    console.log(`switch to ${checked}`);
  };
  //是否上架下拉框
  const type = (value: string) => {
    console.log(`type ${value}`);
  };

  //品牌下拉框
  const Brand = (value: string) => {
    console.log(`Brand ${value}`);
  };
  //时间顺序
  const handleChange = (value: any) => {
    console.log(`handleChange ${value}`);
    sortList({
      name: `${value}`,
      orderNum: '1',
      limit: 7,
      page: 1
    }).then(res => {
      console.log('顺序', res);
      setDataSource(res.data.data)
      // getList()
    }).catch(err => {
      console.log('顺序', err);
    })
  };

  //分类下拉框
  const classify1 = (value: string) => {
    console.log(`classify1 ${value}`);
  };
  const classify2 = (value: string) => {
    console.log(`classify2 ${value}`);
  };

  // 操作部分
  // （1）删除
  // 删除弹框
  const { confirm } = Modal;
  const showConfirm = (record: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除信息吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        // 点击确定发起请求
        deleteById({
          // id: record.Id,
        }).then(res => {
          console.log('删除', res);
          setDataSource(res.data.data)
        }).catch(err => {
          console.log('删除', err);
        })
        console.log('OK', record);
        message.success('删除成功！')
      },
    });
  };



  // 批量删除
  const batchDelete = () => {
    //判断用户是否已选择框
    if (selectedRowKeys.length > 0) {
      showConfirm(selectedRowKeys)
    } else {
      // 发起请求


      // 提示
      message.error('请选择要删除的选项！')
    }

  }


  // （2）修改和查看弹框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  const [isModalOpen1, setIsModalOpen1] = useState<boolean>(false);//是否显示对话框
  const [head, setHead] = useState<string | null>(null);
  const [Revamp, setRevamp] = useState<DataType | null>(null)
  const [che, setCheck] = useState<DataType | null>(null)
  // 修改
  const rev = async (record: any) => {
    setIsModalOpen(true)
    setRevamp(record)
    setHead('修改')
    console.log('(record)----', record);


  }
  // 查看
  const check = (record: any): void => {
    setIsModalOpen1(true)
    setCheck(record)
    console.log('(record)----', record);
    setHead('查看')
  }



  // (5)查询
  const research = async (values: any) => {
    console.log('values----', values);
    message.success('查询成功！')
    let data = ({
      brandName: values.brand,
      goodsName: values.keyword,
      goodsStatus: values.type,
      limit: 4,
      page: 1
    })
    try {
      let res = await researchData(data)
      if (res.code == '200') {
        console.log(res.data);
        setDataSource(res.data.data)
      }
    } catch (err) {
      console.log(err);

    }
  }


  // (4)重置
  const [form] = Form.useForm();//使用From表单，用于默认值
  const reset = () => {
    form.resetFields()
    getList()
    message.success('重置成功！')
  }




  // 自定义添加修改弹框消失
  const modalClose = () => {
    setIsModalOpen(false);

  }
  // 自定义添加修改弹框消失
  const modalClose1 = () => {
    setIsModalOpen1(false);

  }


  return (<div>
    {/* 头部标题 */}
    <p className='head'>商品列表</p>
    {/* 搜索操作 */}
    <Collapse className='collapse' defaultActiveKey={['1']}>
      <Panel header="筛选查询" key="1">
        <div className='operate-wrap'>
          <div className='operate-left'>
            <Form form={form} className='operate-left operate-left-item' onFinish={research}>
              <Form.Item
                label="关键词"
                className='operate-left-item'
                name="keyword"
              // rules={[{ required: true, message: '请输入关键词' }]}
              >
                <Input placeholder="商品名称/商品货号" className='search' />
              </Form.Item>


              <Form.Item label='是否上架：' className='operate-left-item'
                name='type'
              >

                <Select
                  placeholder="请选择"
                  style={{ width: 120 }}
                  className='type'
                  onChange={type}
                  allowClear
                  options={[
                    { value: '4', label: '已上架' },
                    { value: '5', label: '已下架' },

                  ]}
                />

              </Form.Item>
              <Form.Item label='品牌：' className='operate-left-item'
                name='brand'>

                <Select
                  placeholder="请选择"
                  onChange={Brand}
                  style={{ width: 120 }}
                  allowClear
                  options={[{ value: "1", label: '花花公子' }, { value: "2", label: '杜克恩' }, { value: "3", label: '雷哥夫斯' }]}
                  className='drop'
                />

              </Form.Item>

              <Form.Item className='operate-left-item' name='classify1' label='分类:'
              >
                <Select
                  placeholder="请选择一级分类"
                  onChange={classify1}
                  style={{ width: 140 }}
                  allowClear
                  options={[{ value: '青年男士上衣', label: '青年男士上衣' }, { value: '男士', label: '男士' }]}
                  className='drop'
                />
              </Form.Item>


              <Form.Item className='operate-left-item' name='classify2'
              >
                <Select
                  placeholder="请选择二级分类"
                  onChange={classify2}
                  style={{ width: 140 }}
                  allowClear
                  options={[{ value: '青年男士上衣', label: '青年男士上衣' }, { value: '男士', label: '男士' }]}
                  className='drop'
                />
              </Form.Item>

              <Form.Item>
                <Button className='inquire operate-left-item' htmlType='submit'>筛选</Button>
                <Button className='reset' onClick={reset}>重置</Button>

              </Form.Item>
            </Form>


            <Modal title="生成链接" open={isModalOpen3} onOk={handleOk} onCancel={handleCancel} okText="确定" cancelText="取消"
              footer={
                [] // 设置footer为空，去掉 取消 确定默认按钮
              }>
              <Space direction="vertical">
                <Text mark>商品链接为:http://www.toread.clothes.sadfadsfajpei</Text>
              </Space>


            </Modal>
          </div>
        </div>
      </Panel>
    </Collapse>


    {/* 表格列表整体 */}
    < div className='table'>
      {/* 表格操作 */}
      <div className='operationTable'>
        {/* 排序 */}
        <Form>
          <Form.Item label='排序：' className='operate-left-item' name='state' initialValue={stateDefaultValue}>
            <Space wrap>
              <Select
                onChange={handleChange}
                style={{ width: 120 }}
                allowClear
                options={
                  [{ value: "goods_sell", label: '按销量顺序' },
                  { value: 'goods_price_range', label: '按价格顺序' }]}
                className='drop'
              />
            </Space>
          </Form.Item>
        </Form>

        <Button onClick={() => batchDelete()} id='del' className='operate-left-item' >批量删除</Button>




      </div>

    </div >
    {/* 表格 */}
    <ConfigProvider locale={zh_CN}>
      <Table rowSelection={rowSelection} columns={columns} dataSource={dataSource} pagination={{
        position: ['bottomRight'],
        defaultPageSize: 5,
        pageSizeOptions: [3, 5, 10, 15],
        showQuickJumper: true,
        showSizeChanger: true,
      }} />
    </ConfigProvider>
    {/* 修改弹框 */}
    <Add modalClose={modalClose} isModalOpen={isModalOpen} head={head} Revamp={Revamp} getList={getList}></Add>
    <Check modalClose1={modalClose1} isModalOpen1={isModalOpen1} head={head} che={che} ></Check>


  </div >)
}